﻿using iTextSharp.text;
using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.IO;

namespace Turtle
{
	 /// <summary>
	 ///
	 /// </summary>
	 internal class PdfMerge
	 {
		  /// <summary>
		  /// Merges the files.
		  /// </summary>
		  /// <param name="destinationFile">The destination file.</param>
		  /// <param name="sourceFiles">The source files.</param>
		  public static void MergeFiles(string destinationFile, string[] sourceFiles)
		  {
				try
				{
					 int f = 0;

					 // we create a reader for a certain document
					 PdfReader reader = new PdfReader(sourceFiles[f]);

					 // we retrieve the total number of pages
					 int n = reader.NumberOfPages;
					 Console.WriteLine("There are " + n + " pages in the original file.");

					 // step 1: creation of a document-object
					 Document document = new Document(reader.GetPageSizeWithRotation(1));

					 // step 2: we create a writer that listens to the document
					 PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationFile, FileMode.Create));

					 // step 3: we open the document
					 document.Open();
					 PdfContentByte cb = writer.DirectContent;
					 PdfImportedPage page;
					 int rotation;

					 // step 4: we add content
					 while (f < sourceFiles.Length)
					 {
						  int i = 0;
						  while (i < n)
						  {
								i++;
								document.SetPageSize(reader.GetPageSizeWithRotation(i));
								document.NewPage();
								page = writer.GetImportedPage(reader, i);
								rotation = reader.GetPageRotation(i);
								if (rotation == 90 || rotation == 270)
								{
									 cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
								}
								else
								{
									 cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
								}
								Console.WriteLine("Processed page " + i);
						  }
						  f++;
						  if (f < sourceFiles.Length)
						  {
								reader = new PdfReader(sourceFiles[f]);

								// we retrieve the total number of pages
								n = reader.NumberOfPages;
								Console.WriteLine("There are " + n + " pages in the original file.");
						  }
					 }

					 // step 5: we close the document
					 document.Close();
				}
				catch (Exception e)
				{
					 Console.Error.WriteLine(e.Message);
					 Console.Error.WriteLine(e.StackTrace);
				}
		  }

		  /// <summary>
		  /// Merges the streams.
		  /// </summary>
		  /// <param name="destinationFile">The destination file.</param>
		  /// <param name="streams">The streams.</param>
		  public static void MergeStreams(string destinationFile, List<MemoryStream> streams)
		  {
				//I'm going to write my final MemoryStream to a byte array and then to disk
				byte[] bytes;

				//Create our final combined MemoryStream
				using (var finalStream = new MemoryStream())
				{
					 //Create our copy object
					 var copy = new PdfCopyFields(finalStream);

					 //Loop through each MemoryStream
					 foreach (MemoryStream ms in streams)
					 {
						  //Reset the position back to zero
						  ms.Position = 0;

						  //Add it to the copy object
						  copy.AddDocument(new PdfReader(ms));

						  //Clean up
						  ms.Dispose();
					 }

					 //Close the copy object
					 copy.Close();

					 //Get the raw bytes to save to disk
					 bytes = finalStream.ToArray();
				}

				//Write out the file to the destination
				using (var fs = new FileStream(destinationFile, FileMode.Create, FileAccess.Write, FileShare.None))
				{
					 fs.Write(bytes, 0, bytes.Length);
				}
		  }
	 }
}